package com.myapp.web.struts2.interceptor;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.WebApplicationContext;

import com.myapp.util.Constants;
import com.myapp.util.spring.WebPropertyPlaceholderConfigurer;
import com.myapp.util.xwork.PropertiesAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * @see com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor
 * @author peng
 *
 */
public class ActionInjectInterceptor extends AbstractInterceptor implements ApplicationContextAware {

	private static final long serialVersionUID = 8576842181011391060L;
	  private static final Logger LOG = LoggerFactory.getLogger(ActionInjectInterceptor.class);
	  
	private ApplicationContext context = null;
	
	private boolean initialized = false;
	
	protected void initialize(){
		if(initialized || context != null ){
			return;
		}
		ApplicationContext applicationContext = (ApplicationContext)ActionContext.getContext().get(ActionAutowiringInterceptor.APPLICATION_CONTEXT);
		if(applicationContext == null){
			applicationContext = (ApplicationContext)ActionContext.getContext().getApplication().get(
	                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		}
		initialized = true;
		if(LOG.isDebugEnabled()){
			LOG.warn("ApplicationContext could not be found. Action classes can't acquired properties.");
		}
		setApplicationContext(applicationContext);
	}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction();		
		if(action instanceof PropertiesAware){
			if(!initialized){
				initialize();
			}
			Properties props = null;
			if(context != null){
				WebPropertyPlaceholderConfigurer propertyHolder = (WebPropertyPlaceholderConfigurer)context.getBean(Constants.PROPERTY_PLACEHOLDER);
				if(propertyHolder != null){
					props = propertyHolder.getProperties();
				}
			}
			((PropertiesAware)action).setProperties(props);			
		}
		return invocation.invoke();
	}

	@Override
	public void setApplicationContext(ApplicationContext appContext)
			throws BeansException {
		context = appContext;		
	}
}
